﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using DbHelp;
using ICommon;
using System.Runtime.InteropServices;
using System.Diagnostics;
using System.Reflection;
using System.Threading;

namespace IotherRis
{
    static class Program
    {

        static bool mIsRegister = false;

        public static bool MIsRegister
        {
            get { return Program.mIsRegister; }
            set { Program.mIsRegister = value; }
        }

        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main(string[] pAgos)
        {

            //绑定程序中的异常处理
            //BindExceptionHandler();
            DevExpress.UserSkins.OfficeSkins.Register();
            DevExpress.UserSkins.BonusSkins.Register();

            //窗体默认样式
            //string skinName = "Sharp Plus"; //e.Item.Caption.Replace(skinMask, "");
            //DevExpress.LookAndFeel.UserLookAndFeel.Default.SetSkinStyle(skinName);
            //miao mark
            DevExpress.LookAndFeel.UserLookAndFeel.Default.SkinName = "London Liquid Sky";
            DevExpress.Skins.SkinManager.EnableFormSkins();  //窗体边框样式同步


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);


            Application.EnableVisualStyles();

            Application.SetCompatibleTextRenderingDefault(false);


            try
            {
                //进行注册判断
                if (Register.f_isRegister() == false)
                {

                    //return;
                    mIsRegister = false;
                }
                else
                {
                    mIsRegister = true;
                }


            }
            catch
            {
                //MessageBox.Show("注册码错误！");
                // Register.f_cleaRegister();
                //return;
            }

            mIsRegister = true;

            string _filePath = string.Empty;
            if (pAgos.Length > 0)
            {
                _filePath = pAgos[0];
            }
            if (LoadProcess.StarPoint(_filePath, true))
            {
                Fr_main_other _Form = new Fr_main_other(pAgos);
                LoadProcess.LoadProcessMessage _Load = new LoadProcess.LoadProcessMessage(_Form.Handle);

                _Load.LoadMessage += new LoadProcess.LoadProcessMessage.GetMessage(_Load_LoadMessage);

                if (!string.IsNullOrEmpty(_filePath))
                {
                    //  _Form.Text = _filePath;
                }
                Application.Run(_Form);
            }
        }





        /// <summary>
        /// 捕获系统消息的方法
        /// </summary>
        /// <param name="msg"></param>
        static void _Load_LoadMessage(string msg)
        {


            if (!string.IsNullOrEmpty(msg))
            {
                //((Fr_main_other)Application.OpenForms["Fr_main_other"]).Text = msg; //设置标题
                string[] mMsg = new string[] { msg };
                ((Fr_main_other)Application.OpenForms["Fr_main_other"]).MOtherParams = mMsg;
                ((Fr_main_other)Application.OpenForms["Fr_main_other"]).f_tabPages_report(mMsg); //加载文件
                ((Fr_main_other)Application.OpenForms["Fr_main_other"]).Activate(); //激活
                ((Fr_main_other)Application.OpenForms["Fr_main_other"]).BringToFront(); //置前
            }
            ((Fr_main_other)Application.OpenForms["Fr_main_other"]).Visible = true;
            //((Form1)Application.OpenForms["Form1"]).Show();
            ShowWindowAsync(((Fr_main_other)Application.OpenForms["Form1"]).Handle, WS_SHOWNORMAL); //显示，可以注释掉 
            SetForegroundWindow(((Fr_main_other)Application.OpenForms["Form1"]).Handle);    //放到前端 
        }


        /// <summary> 
        /// 该函数将创建指定窗口的线程设置到前台，并且激活该窗口。键盘输入转向该窗口，并为用户改各种可视的记号。系统给创建前台窗口的线程分配的权限稍高于其他线程。 
        /// </summary> 
        /// <param name="hWnd">将被激活并被调入前台的窗口句柄。</param> 
        /// <returns>如果窗口设入了前台，返回值为非零；如果窗口未被设入前台，返回值为零。</returns> 
        [DllImport("User32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);
        private const int WS_SHOWNORMAL = 1;


        /// <summary> 
        /// 显示已运行的程序。 
        /// </summary> 
        public static void HandleRunningInstance(Process instance)
        {


            SetForegroundWindow(instance.MainWindowHandle);            //放到前端 

            //传入参数

        }

        /// <summary> 
        /// 获取正在运行的实例，没有运行的实例返回null; 
        /// </summary> 
        public static Process RunningInstance()
        {
            Process current = Process.GetCurrentProcess();
            Process[] processes = Process.GetProcessesByName(current.ProcessName);
            foreach (Process process in processes)
            {
                if (process.Id != current.Id)
                {
                    if (Assembly.GetExecutingAssembly().Location.Replace("/", "\\") == current.MainModule.FileName)
                    {
                        return process;

                    }
                }
            }
            return null;
        }


        /// <summary>
        /// 绑定程序中的异常处理
        /// </summary>
        private static void BindExceptionHandler()
        {
            //设置应用程序处理异常方式：ThreadException处理
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            //处理未捕获的异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }
        /// <summary>
        /// 处理UI线程异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            LogHelper.ErrorLog(null, e.Exception as Exception);
        }
        /// <summary>
        /// 处理未捕获的异常
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            LogHelper.ErrorLog(null, e.ExceptionObject as Exception);
        }

        //        代码 

        //Code highlighting produced by Actipro CodeHighlighter (freeware)http://www.CodeHighlighter.com/-->  /// 该函数设置由不同线程产生的窗口的显示状态
        //        /// </summary>
        /// <param name="hWnd">窗口句柄</param>
        /// <param name="cmdShow">指定窗口如何显示。查看允许值列表，请查阅ShowWlndow函数的说明部分</param>
        /// <returns>如果函数原来可见，返回值为非零；如果函数原来被隐藏，返回值为零</returns>
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);




        /// <summary>
        /// 本类封装了一些进程间通讯的细节
        /// </summary>
        public class WinMessageUtil
        {
            public const int WM_COPYDATA = 0x004A;

            //通过窗口的标题来查找窗口的句柄
            [DllImport("User32.dll", EntryPoint = "FindWindow")]
            private static extern int FindWindow(string lpClassName, string lpWindowName);

            //在DLL库中的发送消息函数
            //[DllImport("User32.dll", EntryPoint = "SendMessage")]
            //private static extern int SendMessage
            //    (
            //    int hWnd,                        // 目标窗口的句柄  
            //    int Msg,                        // 在这里是WM_COPYDATA
            //    int wParam,                    // 第一个消息参数
            //   ref  ECGExplore.MainForm.CopyDataStruct lParam        // 第二个消息参数
            //   );

            /// <summary>
            /// 发送消息，只能传递一个自定义的消息ID和消息字符串，想传一个结构，但没成功
            /// </summary>
            /// <param name="destProcessName">目标进程名称，如果有多个，则给每个都发送</param>
            /// <param name="msgID">自定义数据，可以通过这个来决定如何解析下面的strMsg</param>
            /// <param name="strMsg">传递的消息，是一个字符串</param>
            public static void SendMessage(string destProcessName, int msgID, string strMsg)
            {
                if (strMsg == null)
                    return;

                //按进程名称查找，同名称的进程可能有许多，所以返回的是一个数组
                Process[] foundProcess = Process.GetProcessesByName(destProcessName);
                foreach (Process p in foundProcess)
                {
                    int toWindowHandler = p.MainWindowHandle.ToInt32();
                    if (toWindowHandler != 0)
                    {
                        // ECGExplore.MainForm.CopyDataStruct cds;
                        // cds.dwData = (IntPtr)msgID;   //这里可以传入一些自定义的数据，但只能是4字节整数      
                        //cds.lpData = strMsg;            //消息字符串
                        // cds.cbData = System.Text.Encoding.Default.GetBytes(strMsg).Length + 1;  //注意，这里的长度是按字节来算的

                        //发送方的窗口的句柄, 由于本系统中的接收方不关心是该消息是从哪个窗口发出的，所以就直接填0了
                        //int fromWindowHandler = 0;
                        // SendMessage(toWindowHandler, WM_COPYDATA, fromWindowHandler, ref  cds);
                    }
                }
            }

            /// <summary>
            /// 接收消息，得到消息字符串
            /// </summary>
            /// <param name="m">System.Windows.Forms.Message m</param>
            /// <returns>接收到的消息字符串</returns>
            public static string ReceiveMessage(ref  System.Windows.Forms.Message m)
            {
                //ECGExplore.MainForm.CopyDataStruct cds = (ECGExplore.MainForm.CopyDataStruct)m.GetLParam(typeof(ECGExplore.MainForm.CopyDataStruct));
                //return cds.lpData;
                return null;
            }
        }
    }
}
